/*
 * FileName: OddEvenSort.java
 * Author:   zzw
 * Date:     2018年05月21日
 * Description:
 */
package com.zzw.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 〈〉<br>
 * 〈〉
 *
 * @author zzw
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本]（可选）
 */
public class OddEvenSort {
    private static int[] arr = new int[]{1,2};
    //private static int[] arr = new int[]{1,2,6,4,5,9,10,12,-1,0};
    private static int exchFlag = 1;
    private static ExecutorService service = Executors.newFixedThreadPool(5);

    public static synchronized void setExchFlag(int v){
        exchFlag = v;
    }

    public static synchronized int getExchFlag(){
        return exchFlag;
    }

    public static class OddEvenSortTask implements Runnable{

        private int i;
        private CountDownLatch latch;

        public OddEvenSortTask(int i,CountDownLatch latch){
            this.i = i;
            this.latch = latch;
        }

        @Override
        public void run() {
            if (arr[i] > arr[i + 1]){
                int temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
                setExchFlag(1);
            }
            latch.countDown();
        }
    }

    public static void pOddEvenSort(int[] arr) throws InterruptedException {
        int start = 0;
        while (getExchFlag() == 1 || start == 1){
            setExchFlag(0);
            CountDownLatch latch = new CountDownLatch(arr.length /2 - (arr.length % 2 == 0 ? start:0));
            for (int i = start;i < arr.length - 1;i += 2){
                service.submit(new OddEvenSortTask(i,latch));
            }
            latch.await();
            if (start == 0){
                start = 1;
            }
            else {
                start = 0;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        pOddEvenSort(arr);
        for (int i = 0;i < arr.length;i++){
            System.out.println(arr[i]);
        }
    }
}
